package com.example.vaccine.service.impl;

import com.example.vaccine.mapper.CheckTasksMapper;
import com.example.vaccine.mapper.VaccineUsageMapper;
import com.example.vaccine.mapper.VaccinesMapper;
import com.example.vaccine.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    private VaccinesMapper vaccineMapper;

    @Autowired
    private VaccineUsageMapper vaccineUsageMapper;

    @Autowired
    private CheckTasksMapper checkTaskMapper;

    public LocalDateTime parseStartTime(String timeRange) {
        LocalDateTime now = LocalDateTime.now();
        switch (timeRange) {
            case "7days":
                return now.minusDays(7);
            case "30days":
                return now.minusDays(30);
            case "all":
            default:
                return null;
        }
    }

    // 疫苗库存 + 接种总览
    public Map<String, Integer> getVaccineOverview(String timeRange) {
        LocalDateTime startTime = parseStartTime(timeRange);

        Integer totalInventory = vaccineMapper.sumAmount();
        Integer totalUsed = vaccineUsageMapper.sumQuantityUsedAfter(startTime);

        Map<String, Integer> result = new HashMap<>();
        result.put("inventoryTotal", totalInventory == null ? 0 : totalInventory);
        result.put("usedTotal", totalUsed == null ? 0 : totalUsed);
        return result;
    }

    // 核查任务状态分布
    public Map<String, Integer> getCheckTaskStatus(String timeRange) {
        LocalDateTime startTime = parseStartTime(timeRange);
        return checkTaskMapper.countStatusAfter(startTime);
    }

    // 疫苗接种量排行
    public List<Map<String, Object>> getVaccineUsageRanking(String timeRange) {
        LocalDateTime startTime = parseStartTime(timeRange);
        return vaccineUsageMapper.selectUsageRanking(startTime);
    }
}
